/**
 * Created by Administrator on 2015/4/3.
 */
var cheerio = require('cheerio'),
    fs = require('fs'),
    ejs = require('ejs'),
    sqlCache = [],
    htmlCache = [];

var EMPTY_REG = /^\s|\s$/;
var EN_LANG = 'En';
var CN_LANG = 'ZnCh'; //todo:为什么是znch

fs.readFile('./faq/source.html', 'utf-8', function (err, data) {
    if (err) {
        throw err;
    }
    var $ = cheerio.load(data, {
            decodeEntities: false
        }),
        $cn = $('#cn'),
        $en = $('#en'),
        questionTemplate = $('#question-template').html(),
        answerTemplate = $('#answer-template').html();
    $en.children('.head').each(function () {
        var header = $(this).find('.guick-guide-head').text(),
            key = getMyFaqKey(header),
            index = $(this).index(),
            $cnHead = $cn.children().eq(index);
        sqlCache.push(new FaqSqlItem(key, header, EN_LANG), new FaqSqlItem(key, $cnHead.text(), CN_LANG));
        htmlCache.push(parseFaqHtmlItem(key, htmlCache.length + 1,
            $(this).next('.body-quick-guide'), $cnHead.next('.body-quick-guide')));
    });

    //generate sql
    var sql = sqlCache.map(function (item) {
        return item.toSqlString();
    }).join('\r\n');
    fs.writeFile('./output/result.sql', sql, 'utf-8', function (err) {
        if (err) {
            throw err;
        }
        console.log('sql success!');
    });

    //generate html
    var questionBox = htmlCache.map(function (item) {
        return item.getRenderedHtml(questionTemplate);
    }).join('');
    var answerBox=htmlCache.map(function (item) {
       return item.getRenderedHtml(answerTemplate);
    }).join('');

    fs.writeFile('./output/result.html',[questionBox,'<div style="clear: both"></div>',answerBox].join(''),
        'utf-8', function (err) {
           if(err){
               throw err;
           }
            console.log('html success');
        });

    function parseFaqHtmlItem(key, ind, $en, $cn) {
        var faqHtmlItem = new FaqHtmlItem(key, ind);
        $en.find('.li-quick-guide').each(function () {
            var index = $(this).index(),
                $cnItem = $cn.find('.li-quick-guide').eq(index),
                qKey = key + '-question-' + index,
                aKey = key + '-answer-' + index;
            faqHtmlItem.CreateFaqItem(qKey, aKey);
            sqlCache.push(
                new FaqSqlItem(qKey, $(this).children('.guick-guide-title').text(), EN_LANG),
                new FaqSqlItem(qKey, $cnItem.children('.guick-guide-title').text(), CN_LANG),
                new FaqSqlItem(aKey, $(this).children('.div-quick-guide').html(), EN_LANG),
                new FaqSqlItem(aKey, $cnItem.children('.div-quick-guide').html(), CN_LANG)
            )
        });
        return faqHtmlItem;
    }
});

var getMyFaqKey = (function (prefix) {
    return function (str) {
        if (!str) {
            return '';
        }
        var underscore = str.replace(EMPTY_REG, '').replace(' ', '_').toLowerCase();
        return prefix + underscore;
    }
})('my-faq-');

function FaqSqlItem(key, value, lang) {
    this.key = key;
    this.value = value;
    this.lang = lang;
}

FaqSqlItem.prototype.User = 'Admin';

FaqSqlItem.prototype.toSqlString = function () {
    var tempSql = "insert into dbo.[LanguageResource] " +
        "([ResourceKey],[Culture],[LanguageType],[Value],[CreateBy],[UpdateBy],[CreateDate],[UpdateDate]) " +
        "values(N'<%- key %>',N'<%- lang %>',N'Csharp',N'<%= value %>',N'<%- User %>',N'<%- User %>',GETDATE(),GETDATE())";
    return ejs.render(tempSql, this);
};

//
function FaqHtmlItem(key, index) {
    this.key = key;
    this.items = [];
    this.index = index;
}

FaqHtmlItem.prototype.CreateFaqItem = function (q, a) {
    this.items.push({q: q, a: a});
};

FaqHtmlItem.prototype.getRenderedHtml = function (template) {
    return ejs.render(template, this);
};


